package com.baijiayun.live.ui.pptpanel.pptmanage

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.baijia.bjydialog.DialogAction
import com.baijia.bjydialog.MaterialDialog
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.activity.LiveRoomBaseActivity
import com.baijiayun.live.ui.activity.LiveRoomRouterListener
import com.baijiayun.live.ui.base.RouterViewModel
import com.baijiayun.livecore.context.LiveRoom
import com.baijiayun.livecore.models.LPUploadDocModel
import com.baijiayun.livecore.models.LPUploadHomeworkUserModel
import com.baijiayun.livecore.models.courseware.LPMediaCoursewareModel
import com.baijiayun.livecore.models.file.cloudfile.LPCloudFileModel
import com.baijiayun.livecore.models.roomresponse.LPAllowUploadHomeworkModel
import com.baijiayun.livecore.utils.ToastCompat
import com.baijiayun.livecore.viewmodels.impl.LPDocListViewModel.DocModel
import com.baijiayun.liveuibase.base.BaseUIConstant.UploadType
import com.baijiayun.liveuibase.widgets.courseware.BaseCourseWareContract.BaseCourseWarePresenter
import com.baijiayun.liveuibase.widgets.courseware.BaseCourseWareView
import com.baijiayun.liveuibase.widgets.courseware.CourseManagePresenter
import com.baijiayun.liveuibase.widgets.courseware.ICourseWareViewListener
import com.baijiayun.liveuibase.widgets.courseware.models.UploadDocModel
import com.baijiayun.liveuibase.widgets.dialog.ThemeMaterialDialogBuilder
import java.util.*
import kotlin.math.max

class PPTManageWindow : BaseCourseWareView() {
    private var routerViewModel: RouterViewModel? = null
    private var routerListener: LiveRoomRouterListener? = null
    private var pageIndexCaches: MutableMap<String, Int>? = null
    override fun initChildData() {
        pageIndexCaches = HashMap()
        if (context is LiveRoomBaseActivity) {
            routerListener = (context as LiveRoomBaseActivity).routerListener
            routerViewModel = ViewModelProvider(context as LiveRoomBaseActivity).get(RouterViewModel::class.java)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = super.onCreateView(inflater, container, savedInstanceState)
        presenter.subscribe(routerListener!!.liveRoom)
        return view
    }

    override fun initCourseWareViewListener(): ICourseWareViewListener {
        return object : ICourseWareViewListener {
            override fun onClose() {
                routerViewModel!!.actionShowPPTManager.value = false
            }

            override fun onUploadFile(uploadType: UploadType) {
                routerViewModel!!.actionChooseFiles.value = uploadType
            }

            override fun onPlayImg(uploadDocModel: LPUploadDocModel) {
                playDoc(uploadDocModel.fileId.toString())
            }

            override fun onReminderMsg(msg: String) {
                ToastCompat.showToast(getContext(), msg, Toast.LENGTH_SHORT)
            }

            override fun onRemindHomeworkSupport() {
                ThemeMaterialDialogBuilder(context)
                        .content(R.string.base_course_manage_homework_support_remind_text)
                        .positiveText(R.string.base_live_i_know)
                        .negativeText(R.string.base_do_not_remind)
                        .onNegative { dialog: MaterialDialog?, which: DialogAction? -> homeworkRemindStatus = HomeworkRemindStatus.DoNotRemind }
                        .autoDismiss(true).build().show()
            }

            override fun onDeleteDoc(fid: String, isReUpload: Boolean) {
                if (isReUpload) {
                    routerViewModel!!.liveRoom.docListVM.deleteDocument(fid)
                } else {
                    ThemeMaterialDialogBuilder(context)
                        .content(R.string.base_course_manage_delete_doc_reminder)
                        .positiveText(R.string.base_course_manage_delete_confirm)
                        .positiveColor(ContextCompat.getColor(context, R.color.base_warning_color))
                        .onPositive { dialog: MaterialDialog?, which: DialogAction? -> routerViewModel!!.liveRoom.docListVM.deleteDocument(fid) }
                        .negativeText(R.string.base_cancel)
                        .autoDismiss(true).build().show()
                }
            }

            override fun onDeleteMediaCourseware(fid: String?) {
                // do nothing
            }

            override fun onDeleteCloudFile(cloudFileModel: LPCloudFileModel) {
                ThemeMaterialDialogBuilder(context)
                        .content(R.string.base_course_manage_delete_doc_reminder)
                        .positiveText(R.string.base_course_manage_delete_confirm)
                        .positiveColor(ContextCompat.getColor(context, R.color.base_warning_color))
                        .onPositive { dialog: MaterialDialog?, which: DialogAction? -> routerViewModel!!.liveRoom.cloudFileVM.deleteCloudFile(cloudFileModel.fileId) }
                        .negativeText(R.string.base_cancel)
                        .autoDismiss(true).build().show()
            }

            override fun onDeleteHomework(homeworkId: String) {
                ThemeMaterialDialogBuilder(context)
                        .content(R.string.base_course_manage_delete_homework_reminder)
                        .positiveText(R.string.base_course_manage_delete_confirm)
                        .positiveColor(ContextCompat.getColor(context, R.color.base_warning_color))
                        .onPositive { dialog: MaterialDialog?, which: DialogAction? ->
                            presenter.deleteHomework(homeworkId,
                                    LPUploadHomeworkUserModel.copyData(routerViewModel!!.liveRoom.currentUser))
                        }
                        .negativeText(R.string.base_cancel)
                        .autoDismiss(true).build().show()
            }

            override fun onCancelTransfer(uploadDocModel: UploadDocModel) {
                ThemeMaterialDialogBuilder(context)
                        .content(R.string.base_course_manage_cancel_transfer_reminder)
                        .positiveText(R.string.base_course_manage_delete_confirm)
                        .positiveColor(ContextCompat.getColor(context, R.color.base_warning_color))
                        .onPositive { dialog: MaterialDialog?, which: DialogAction? -> presenter.deleteTranslating(uploadDocModel) }
                        .negativeText(R.string.base_cancel)
                        .autoDismiss(true).build().show()
            }

            override fun onUpdateAllowUploadHomework(isAllow: Boolean) {
                routerViewModel!!.liveRoom.docListVM.requestUpdateAllowUploadHomework(
                        LPAllowUploadHomeworkModel(isAllow))
            }

            override fun requestLoadNextPage(keyword: String) {
                routerViewModel!!.liveRoom.docListVM.requestNextPageHomework(keyword)
            }
        }
    }

    override fun initPresenter(): BaseCourseWarePresenter {
        return object : CourseManagePresenter(this) {
            override fun playDoc(docModel: DocModel):Boolean {
                return this@PPTManageWindow.playDoc(docModel.docId)
            }

            override fun playMediaCourseware(toPlayMedia: LPMediaCoursewareModel?) {
                ToastCompat.showToast(
                    this@PPTManageWindow.context,
                    this@PPTManageWindow.context.getString(R.string.base_course_manage_file_type_not_support_play),
                    Toast.LENGTH_LONG
                )
            }

            override fun playBds(bdsModel: DocModel) {
                // do nothing
            }
        }
    }

    private fun playDoc(docId: String):Boolean {
        if (routerListener != null) {
            val page: Int
            val index = pageIndexCaches!![docId]
            page = index ?: findDocListFirstPage(docId)
            routerListener!!.notifyPageCurrent(page)
        }
        return true
    }

    private fun findDocListFirstPage(docId: String): Int {
        val docList = routerListener!!.liveRoom.docListVM.docList
        var pageTotal: Int
        var i = 0
        while (i < docList.size) {
            val docModel = docList[i]
            pageTotal = docModel.totalPage
            pageIndexCaches!![docModel.docId] = docModel.page
            i += max(1,pageTotal)
        }
        val index = pageIndexCaches!![docId]
        return index ?: 0
    }

    override fun getLiveRoom(): LiveRoom? {
        return if (routerViewModel == null) {
            null
        } else routerViewModel!!.liveRoom
    }

    override fun onDestroy() {
        super.onDestroy()
        routerViewModel = null
        routerListener = null
    }
}